<!--  -->
<template>
  <div class="signBox" id="longbox">
    <!-- 导航栏 -->
    <div class="tab-bar">
      <van-nav-bar left-arrow @click-left="$router.go(-1)" :border="false">
        <span class="headline" slot="title">手写签名</span>
      </van-nav-bar>
    </div>
    <div class="boardBox" ref="boardBox" id="chatContainer">
      <canvas
        ref="board"
        @touchstart="mStart"
        @touchmove="mMove"
        @touchend="mEnd"
      ></canvas>
    </div>
    <div class="signFoot">
      <!-- 选择颜色 -->
      <div class="colorSelect">
        <span
          class="selectColor"
          :class="colorsecectindex === 1 ? 'colorSpan' : ''"
          @click="blackcolor"
          >✓</span
        >
        <span
          class="selectColor"
          @click="redcolor"
          :class="colorsecectindex === 2 ? 'colorSpan' : ''"
          >✓</span
        >
        <span
          class="selectColor"
          @click="bluecolor"
          :class="colorsecectindex === 3 ? 'colorSpan' : ''"
          >✓</span
        >
      </div>
      <!-- 取消保存按钮 -->
      <div class="signBut">
        <van-button class="delectSign" type="default" @click="cleanCanvas"
          >清除</van-button
        >
        <van-button class="saveBut" type="info" @click="saveCanvas"
          >确定</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { addSealSignature } from '@/api/user'
export default {
  components: {},
  data: () => ({
    ctx: null,
    point: {
      x: 0,
      y: 0
    },
    moving: false, // 是否正在绘制中且移动
    // base64图片
    signImg1: '',
    // 判断选择那个
    colorsecectindex: 1
  }),

  computed: {},
  mounted() {
    this.init()
    // 阻止页面的滑动默认事件
    window.addEventListener(
      'touchmove',
      function(e) {
        // 1.2 如果碰到滑动问题，请注意是否获取到 touchmove
        e.preventDefault() // 阻止冒泡事件
      },
      { passive: false }
    )
  },
  created() {},

  methods: {
    // 自动适配宽高
    init() {
      const board = this.$refs.board // 获取DOM
      this.width = board.width = this.$refs.boardBox.offsetWidth // 设置画布宽
      this.height = board.height = this.$refs.boardBox.offsetHeight // 设置画布高
      this.ctx = board.getContext('2d') // 二维绘图
      this.ctx.strokeStyle = '#000' // 颜色
      this.ctx.lineWidth = 3 // 线条宽度
    },
    mStart(e) {
      // console.log(e);
      const x = e.touches[0].clientX - e.target.offsetLeft
      const y = e.touches[0].clientY - e.target.offsetTop // 获取触摸点在画板（canvas）的坐标
      this.point.x = x
      this.point.y = y
      this.ctx.beginPath()
      this.moving = true
    },
    // 滑动中...
    mMove(e) {
      if (this.moving) {
        const x = e.touches[0].clientX - e.target.offsetLeft
        const y = e.touches[0].clientY - e.target.offsetTop // 获取触摸点在画板（canvas）的坐标
        this.ctx.moveTo(this.point.x, this.point.y) // 把路径移动到画布中的指定点，不创建线条(起始点)
        this.ctx.lineTo(x, y) // 添加一个新点，然后创建从该点到画布中最后指定点的线条，不创建线条
        this.ctx.stroke() // 绘制
        this.point.x = x
        this.point.y = y // 重置点坐标为上一个坐标
      }
    },
    // 选择画笔颜色
    blackcolor() {
      this.ctx.strokeStyle = '#000'
      this.colorsecectindex = 1
    },
    redcolor() {
      this.ctx.strokeStyle = 'red'
      this.colorsecectindex = 2
    },
    bluecolor() {
      this.ctx.strokeStyle = '#2489f2'
      this.colorsecectindex = 3
    },
    // 滑动结束
    mEnd() {
      if (this.moving) {
        this.ctx.closePath() // 停止绘制
        this.moving = false // 关闭绘制开关
      }
    },
    // 清除画布
    cleanCanvas() {
      // clearRect() 方法清空给定矩形内的指定像素。
      this.ctx.clearRect(0, 0, this.width, this.height)
    },
    // 保存
    async saveCanvas() {
      const that = this
      const edg = 90
      const src = this.$refs.board.toDataURL()
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      var imgW // 图片宽度
      var imgH // 图片高度
      var size // canvas初始大小
      const quadrant = (edg / 90) % 4 // 旋转象限
      const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 } // 裁剪坐标
      var image = new Image()
      image.crossOrigin = 'anonymous'
      image.src = src
      image.onload = function() {
        imgW = image.width
        imgH = image.height
        size = imgW > imgH ? imgW : imgH
        canvas.width = size * 2
        canvas.height = size * 2
        switch (quadrant) {
          case 0:
            cutCoor.sx = size
            cutCoor.sy = size
            cutCoor.ex = size + imgW
            cutCoor.ey = size + imgH
            break
          case 1:
            cutCoor.sx = size - imgH
            cutCoor.sy = size
            cutCoor.ex = size
            cutCoor.ey = size + imgW
            break
          case 2:
            cutCoor.sx = size - imgW
            cutCoor.sy = size - imgH
            cutCoor.ex = size
            cutCoor.ey = size
            break
          case 3:
            cutCoor.sx = size
            cutCoor.sy = size - imgW
            cutCoor.ex = size + imgH
            cutCoor.ey = size + imgW
            break
        }
        ctx.translate(size, size)
        ctx.rotate((edg * Math.PI) / 180) // drawImage向画布上绘制图片
        ctx.drawImage(image, 0, 0) // getImageData()复制画布上指定矩形的像素数据
        var imgData = ctx.getImageData(
          cutCoor.sx,
          cutCoor.sy,
          cutCoor.ex,
          cutCoor.ey
        )
        if (quadrant % 2 === 0) {
          canvas.width = imgW
          canvas.height = imgH
        } else {
          canvas.width = imgH
          canvas.height = imgW
        } // putImageData()将图像数据放回画布
        ctx.putImageData(imgData, 0, 0)
        that.image1 = canvas.toDataURL()
      }
      this.cleanCanvas()
      const { data: res } = await addSealSignature({ image: this.image })
      if (res.code !== '0') {
        return this.$toast.fail('添加签名失败!')
      }
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.signBox {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  /* background: url(pic.jpg) no-repeat #000; */
  background-color: #e4e4e4;
  background-size: cover; /* 铺满屏幕，屏幕变小，图片可能显示不下 */
  background-size: 100% 100%; /* 铺满屏幕，随屏幕变化而变化比例，图片可能被拉伸 */
  .tab-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88px;
    background-color: #fff;
    z-index: 44;
    .van-nav-bar {
      .headline {
        font-size: 34px;
        font-weight: bold;
      }
      /deep/.van-icon {
        font-size: 40px;
        color: #101010;
      }
    }
    /deep/.van-nav-bar__left {
      padding-left: 23px;
    }
  }
  .boardBox {
    width: 100vw;
    height: 100vh;
    background: #f9f9f9;
    canvas {
      // border: 1px solid #b3b3b3;
    }
  }
  .signFoot {
    position: absolute;
    right: 0;
    top: 46vh;
    width: 100vh;
    height: 15vw;
    transform: rotate(90deg);
    display: flex;
    justify-content: space-between;
    .colorSelect {
      margin-left: 208px;
      .selectColor {
        display: inline-block;
        margin-right: 60px;
        width: 60px;
        height: 60px;
        background-color: #e4e4e4;
        border-radius: 50%;
        text-align: center;
        line-height: 60px;
        overflow: hidden;
      }
      span:nth-child(1) {
        background-color: #000;
        color: #000;
      }
      span:nth-child(2) {
        background-color: red;
        color: red;
      }
      span:nth-child(3) {
        background-color: #2489f2;
        color: #2489f2;
      }
      .colorSpan {
        color: white !important;
      }
    }
    .signBut {
      margin-right: 72px;
      .van-button {
        width: 120px;
        height: 80px;
      }
      .delectSign {
        margin-right: 52px;
      }
    }
  }
}
</style>
